import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {DialogService} from "../../../service/dialogService";
import {CCRiskControllerService} from "../../../service/CCRiskController";
import {WeUINavBarItem} from "angular4-weui";
import {Subject} from "rxjs/Subject";
import {FileService} from "../../../service/fileService";
import {UIRiskTaskCriteria} from "../../../entity/UIRiskTaskCriteria";
import {RestRiskCheckTask} from "../../../entity/RestRiskCheckTask";
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';
import 'rxjs/add/operator/switchMap';
import {WeUIPicker} from "angular4-weui";
import {BaseAuthenticateComponent} from "../../../components/baseAuthenticateComponent";
import {JsSdkService} from "../../../service/jsSdkService";
import {RestRiskInfo} from "../../../entity/RestRiskInfo";
import {UIRiskCheckExecution} from "../../../entity/UIRiskCheckExecution";
import {UICCProcessTaskExtension4ExecutionCriteria} from "../../../entity/UICCProcessTaskExtension4ExecutionCriteria";
declare var wx: any;
@Component({
  selector: 'app-risk-check',
  templateUrl: './risk-check.component.html',
  styleUrls: ['./risk-check.component.css']
})
export class RiskCheckComponent implements OnInit {

  static activeTab = '1';
  static taskProcessingCount = 0;
  static taskFinishedCount = 0;

  activeValue: string;
  searchStream = new Subject<string>();
  taskTypeList: any = {};

  uiCriteria: UIRiskTaskCriteria = new UIRiskTaskCriteria();
  uiExecutionCriteria: UICCProcessTaskExtension4ExecutionCriteria = new UICCProcessTaskExtension4ExecutionCriteria();
  valuesForRiskCheckTaskList: RestRiskCheckTask[] = [];
  valuesForRiskCheckExectionList: UIRiskCheckExecution[] = [];
  skipFlag = 1;
  loadMore = false;
  remindTxt = '';
  totalRecord: number;

  value: any[] = [
    {
      label: '全部',
      value: ''
    }
  ];

  taskMenu: any[] = [
    {
      label: '日常检查',
      value: 'CCRiskCheckExecutionRoutineProcess'
    }, {
    label: '专项检查',
    value: 'CCRiskCheckExecutionProcess'
  }, {
    label: '二维码位置检查',
    value: 'CCRiskCheckExecutionDimensionProcess'
  },{
      label: '全部',
      value: ''
    }
  ];
  filterType: string;
  url: string;
  submitInfo: RestRiskInfo = new RestRiskInfo();

  @ViewChild('picker1') picker1: WeUIPicker;

  constructor(protected a_router: Router, public element: ElementRef, public fileService: FileService,
              public _jsSdkService: JsSdkService,
              public route: ActivatedRoute, public _dialogService: DialogService, public riskService: CCRiskControllerService) {
    //解决微信扫一扫问题 android和ios系统签名所用url不同 android系统 需要刷新页面
    // const tag = localStorage.getItem("refreshTag");
    // if ( (!(/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent))) && (tag !== 'true') ) {
    //   localStorage.setItem('refreshTag', 'true');
    //   window.location.reload();
    // }
  }

  ngOnInit() {
    this.uiCriteria.pagesize = 10;
    this.uiCriteria.skip = 0;
    this.activeValue = RiskCheckComponent.activeTab;
    this.searchStream
      .pipe(
        debounceTime(500),     // wait for 500ms pause in events
        distinctUntilChanged() // ignore if next search term is same as previous
      )
      .subscribe((term: string) => {
        this.uiCriteria.description = term;
        this.getTaskByStatus();
      });
  }

  ngAfterViewInit() {
    this.searchStream.next("");
  }

  /**
   * 微信 JSSDK 配置
   */
  configJSSDK() {
    this.url = location.href.split('#')[0];
    //由于Android和iOS微信签名时所用的url不同,区别对待
    if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
      this.url = localStorage.getItem("initURL");

    }

    this._jsSdkService.getSignature(this.url).subscribe(
      (signature) => {
        wx.config({
          debug: false,
          appId: signature.data.appid,
          timestamp: signature.data.timestamp,
          nonceStr: signature.data.nonceStr,
          signature: signature.data.signature,
          jsApiList: ['scanQRCode']
        });
      }
    );
  }

  getTaskTypeList() {
    this.riskService.getTaskTypeList().subscribe(
      (res) => {
        this.taskTypeList = res.value;
      }
    );
  }

  refreshRiskTaskList() {
    // 只筛选隐患排查任务
    if (this.uiCriteria.taskType === '' || !this.uiCriteria.taskType) {
      this.uiCriteria.taskType = 'CCRiskCheck%';
    }

    console.log('*** refreshRiskTaskList *** ' + JSON.stringify(this.uiCriteria))
    this.riskService.taskList(this.uiCriteria).subscribe(
      (res) => {
        if (res) {
          this.valuesForRiskCheckTaskList = res.result;
          this.totalRecord = res.totalRecord;
          if (this.activeValue === '1') {
            // 未完成任务数量
            RiskCheckComponent.taskProcessingCount = res.totalRecord;
          } else {
            // 完成任务数量
            // 已完成任务不用task 用execution
            this.valuesForRiskCheckTaskList = this.valuesForRiskCheckTaskList.filter((riskCheckTask) => riskCheckTask.riskCheckExecution.status === 'finished');
            this.valuesForRiskCheckTaskList = this.valuesForRiskCheckTaskList.sort((a, b) => b.id - a.id);
            RiskCheckComponent.taskFinishedCount = this.valuesForRiskCheckTaskList.length;
            this.totalRecord = this.valuesForRiskCheckTaskList.length;
          }

          this.loadMore = this.totalRecord > this.valuesForRiskCheckTaskList.length;

          if (!this.valuesForRiskCheckTaskList || this.valuesForRiskCheckTaskList.length === 0) {
            this.remindTxt = '暂无数据';
          } else {
            this.remindTxt = this.valuesForRiskCheckTaskList.length + " / " + this.totalRecord;
          }
        }
      }
    );
  }

  getFinishedRiskExecutionList() {

    this.uiExecutionCriteria.status = ['finished'];
    this.riskService.executionList(this.uiExecutionCriteria).subscribe(
      (res) => {
        if (res) {
          this.valuesForRiskCheckExectionList = res.result;
          this.totalRecord = res.totalRecord;
          RiskCheckComponent.taskFinishedCount = res.totalRecord;

          this.loadMore = this.totalRecord > this.valuesForRiskCheckExectionList.length;

          if (!this.valuesForRiskCheckExectionList || this.valuesForRiskCheckExectionList.length === 0) {
            this.remindTxt = '暂无数据';
          } else {
            this.remindTxt = this.valuesForRiskCheckExectionList.length + " / " + this.totalRecord;
          }
        }
      }
    );
  }

  onActivated(item: WeUINavBarItem): void {
    // 恢复滚动条的垂直位置,从头开始
    this.skipFlag = 1;
    this.loadMore = false;
    this.activeValue = item.value;
    RiskCheckComponent.activeTab = this.activeValue;
    if (this.activeValue === '1') {
      this.uiCriteria.pagesize = 10;
      this.uiCriteria.skip = 0;
    } else {
      this.uiExecutionCriteria.pagesize = 10;
      this.uiExecutionCriteria.skip = 0;
    }
    // 解决频繁切换tab问题
    this.getTaskByStatus();
    // this.searchStream.next(this.uiCriteria.description);
  }

  getTaskByStatus() {
    switch (this.activeValue) {
      case '1':
        this.uiCriteria.status = 'processing';
        this.refreshRiskTaskList();
        break;
      case '2':
        this.getFinishedRiskExecutionList();
        break;
    }
  }

  onScroll() {
    this.uiCriteria.skip = this.uiCriteria.pagesize * this.skipFlag;
    console.log(JSON.stringify(' totalRecord =======> ' + this.totalRecord));
    this.riskService.taskList(this.uiCriteria).subscribe(
      res => {
        this.valuesForRiskCheckTaskList = this.valuesForRiskCheckTaskList.concat(res.result)
        if (this.totalRecord > this.valuesForRiskCheckTaskList.length) {
          this.loadMore = true;
          // this.remindTxt = "查看更多";
          this.skipFlag++;
        } else {
          this.loadMore = false;
          // this.remindTxt = "数据已加载完";
        }
        this.remindTxt = this.valuesForRiskCheckTaskList.length + " / " + this.totalRecord;
      }
    );
  }

  search(value: string): void {
    this.uiCriteria.skip = 0;
    this.skipFlag = 1;
    this.searchStream.next(value);
  }

  detail(event: RestRiskCheckTask) {
    this.a_router.navigate(["/dashboard/task", event.id, "detail"]);
  }

  actionHandle(event: RestRiskCheckTask) {
    this.submitInfo.comment = '初查完成';
    this.riskService.startCheckCompleted(event.id, this.submitInfo).subscribe(
      () => {
        this.refreshRiskTaskList();
      }
    );
  }

  executionDetail(event: UIRiskCheckExecution) {
    this.a_router.navigate(["/dashboard/plan/execution", event.id, "detail"]);
  }

  showPicker() {
    this.picker1.show().then((value: any) => {
      this.filterType = value[0].label;
      this.uiCriteria.taskType = value[0].value;
      this.uiCriteria.skip = 0;
      this.skipFlag = 1;
      this.refreshRiskTaskList();
    });
  }

  scan() {
    wx.scanQRCode({
      needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
      scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码，默认二者都有
      success: (res) => {
        window.location.href = 'dashboard/task/' + res.resultStr + '/qrTaskList';
        // this.a_router.navigate(["dashboard/task", res.resultStr, "qrTaskList"]);
      }
    });
  }

  getTabActivated() {
    return RiskCheckComponent.activeTab;
  }

  getProcessingCount() {
    return RiskCheckComponent.taskProcessingCount;
  }

}
